﻿using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using OpenHardwareMonitor.Hardware;
using OpenHardwareMonitorJsonServer.Utilities;

using System;
using System.Net;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace OpenHardwareMonitorJsonServer
{
    public partial class ServerOptionForm : Form
    {            
        private HttpServer server;
        private bool severStarted = false;

        public ServerOptionForm()
        {
            server = new HttpServer(8085);

            InitializeComponent();
            
            if (!severStarted)
                server.StartHTTPListener();
        }

        private async static void StartServer(Computer computer)
        {
            var visitor = new Visitor();

            // Start a HTTP server on port 8080.
            var listener = new HttpListener();
            listener.Prefixes.Add("http://localhost:8080/");
            listener.Start();

            // While the server is still running...
            while (listener.IsListening)
            {
                // Context is an incoming HTTP request.
                var context = await listener.GetContextAsync();
                // Update the sensors.
                computer.Accept(visitor);
                // Serialize the data in computer.Hardware into a JSON string, ignoring circular references.
                // NOTE: The circular reference is from each node having a reference to its parent.
                // TODO: The data can be cleaned up some before serializing, it contains a bunch of extraneous data.
                // The serializer in OpenHardwareMonitor's GUI library used by its own JSON server simply collects
                // the values to serialize. It can serve as a starting point.
                var settings = new JsonSerializerSettings()
                {
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                    ContractResolver = new CustomContractResolver()
                };
                var data = JsonConvert.SerializeObject(computer.Hardware, settings);

                var buffer = Encoding.UTF8.GetBytes(data);
                var response = context.Response;

                try
                {
                    response.AddHeader("Access-Control-Allow-Origin", "*");
                    response.AddHeader("Content-Type", "application/json");
                    response.OutputStream.Write(buffer, 0, buffer.Length);
                }
                catch (HttpListenerException)
                {
                    // Don't do anything, this is most likely caused by the client ending the TCP connection, and
                    // therefore writing to the closed TCP connection will throw an exception.
                }

                response.OutputStream.Close();
            }
        }

        //最小化事件,显示到托盘  
        private void ServerOptionForm_Resize(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Visible = false;
            }
        }
        //托盘图标单击显示  
        private void trayNotifyIcon_MouseClick(object sender, MouseEventArgs e)
        {
            //if(this.Visible)
            //{
            //    this.Visible = false;
            //}
            //else
            //{
            //    this.Visible = true;
            //    this.TopMost = true;
            //    this.WindowState = FormWindowState.Normal;
            //    this.Activate();
            //}

        }
        //假关闭,关闭时隐藏  
        private void ServerOptionForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            this.Visible = false;
        }

        private void Show_ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Show();
            WindowState = FormWindowState.Normal;
        }

        private void Quit_ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
            if (MessageBox.Show("是否确认退出程序？", "退出", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                server.Quit();

                this.Dispose();//关闭占用的资源
                this.Close();
            }
        }

        private void btnTest_Click(object sender, EventArgs e)
        {
            //var settings = new JsonSerializerSettings()
            //{
            //    ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
            //    ContractResolver = new CustomContractResolver()
            //};

            //var data = JsonConvert.SerializeObject(computer.Hardware, settings);

            //var buffer = Encoding.UTF8.GetBytes(data);

            //this.textComputer.Text = data;
        }  

    }
}
